package com.ssm.service.impl;

import com.ssm.common.Const;
import com.ssm.common.ServerResponse;
import com.ssm.common.TokenCache;
import com.ssm.entity.pojo.MmallUser;
import com.ssm.mapper.MmallUserMapper;
import com.ssm.service.IUserService;
import com.ssm.util.MD5Util;
import com.sun.tools.classfile.ConstantPool;
import net.sf.jsqlparser.schema.Server;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service("iUserService")
public class UserServiceImpl implements IUserService {
    @Autowired
    private MmallUserMapper mmallUserMapper;

    /*
    * 登陆服务
    * */
    public ServerResponse<MmallUser> login(String username, String password) {
//        MmallUser e = new MmallUser();
//        e.setUsername(username);
//        e.setPassword(password);
//        MmallUser mmallUser = mmallUserMapper.selectLogin(e);
        Map<String,Object> params = new HashMap<String, Object>();
        params.put("username",username);
        password = MD5Util.MD5EncodeUtf8(password);
        params.put("password",password);
        MmallUser mmallUser = mmallUserMapper.selectLogin(params);
        if(mmallUser == null){
            return ServerResponse.createByErrorMessage("用户或密码错误");

        }
        return ServerResponse.createBySuccess("登陆成功",mmallUser);

    }
    /*
    * 用户注册
    * */
    public ServerResponse<String> register(MmallUser user) {        //springmvc 数据绑定
        //检查用户名是否存在,Email是否存在
        //int resoultCount = checkValid(user.getUsername(), Const.USERNAME);

        int resoultCount = mmallUserMapper.checkUsername(user.getUsername());
        if(resoultCount > 0){
            return ServerResponse.createByErrorMessage("用户已经存在");
        }
        resoultCount = mmallUserMapper.checkEmail(user.getEmail());
        if(resoultCount > 0){
            return ServerResponse.createByErrorMessage("邮箱已经存在");
        }

        //校验成功
        user.setRole(Const.Role.ROLE_CUSTOMER);
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
//        insert一般返回插入的目录数量
        resoultCount = mmallUserMapper.insertUser(user);

        if(resoultCount == 0){
            return ServerResponse.createByError();
        }

        return ServerResponse.createBySuccessMessage("注册成功");

    }

    public ServerResponse<String> checkValid(String str, String strType) {
       if(StringUtils.isNotBlank(strType)){ //isNotBlank 不是一个空格
           //开始校验
           if(Const.USERNAME.equals(strType)){
               int resoultCount = mmallUserMapper.checkUsername(str);
               if(resoultCount > 0){
                   return ServerResponse.createByErrorMessage("用户已经存在");
               }
           }
           if(Const.EMAIL.equals(strType)){
               int resoultCount = mmallUserMapper.checkEmail(str);
               if(resoultCount > 0){
                   return ServerResponse.createByErrorMessage("邮箱已经存在");
               }
           }
       }else{
           return ServerResponse.createByErrorMessage("参数错误");
       }
       return ServerResponse.createBySuccessMessage("参数合法");
    }



    public ServerResponse<String> selectQuestionByUsername(String username) {
        //校验用户名
        ServerResponse response = this.checkValid(username,Const.USERNAME);
        if(response.isSuccess()){
            //用户名不存在
            return ServerResponse.createByErrorMessage("用户不存在");

        }
        String question = mmallUserMapper.selectQuestionByUsername(username);
        if(StringUtils.isNoneBlank(question)){
            return ServerResponse.createBySuccess(question);
        }
        //如果用户问题为空
        return ServerResponse.createByErrorMessage("用户问题为空");
    }

    public ServerResponse<String> checkAnswer(String username, String question, String answer) {
        Map<String,String> params = new HashMap<String, String>();
        params.put("username",username);
        params.put("question",question);
        params.put("answer",answer);
        int responseCount = mmallUserMapper.checkAnswer(params);
        if(responseCount > 0 ){
            String forgetToken = UUID.randomUUID().toString();
            TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);
            return ServerResponse.createBySuccess(forgetToken);
        }else{
            return ServerResponse.createByErrorMessage("问题答案错误");
        }
    }

    public ServerResponse<String> forgetResetPassword(String username,String passwordnew ,String forgetToken){

        if(StringUtils.isBlank(forgetToken)){
            return  ServerResponse.createByErrorMessage("token未传入");
        }
        ServerResponse response = this.checkValid(username,Const.USERNAME);
        if(response.isSuccess()){
            //用户名不存在
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);
        if(StringUtils.isBlank(token)){
            return ServerResponse.createByErrorMessage("token无效或者过期");
        }
        //校验token
        if(StringUtils.equals(forgetToken,token)){
            passwordnew = MD5Util.MD5EncodeUtf8(passwordnew);
            int e = mmallUserMapper.updatePasswordByUsername(username,passwordnew);
            if(e > 0){
                return ServerResponse.createBySuccessMessage("修改密码成功");
            }
        }else{
            return ServerResponse.createBySuccessMessage("token错误，重新获取token");
        }

        return  ServerResponse.createBySuccessMessage("密码修改失败");
    }

    public ServerResponse<String> resetPassword(MmallUser user, String passwordold, String passwordnew) {
        //先检查密码是否错误
        Map<String,Object> params = new HashMap<String, Object>();
        params.put("password",MD5Util.MD5EncodeUtf8(passwordold));
        params.put("id",user.getId());
        int responseCount = mmallUserMapper.checkPasswordById(params);
        if(responseCount == 0){
            return ServerResponse.createByErrorMessage("原密码错误");
        }
        responseCount = mmallUserMapper.updatePasswordByUsername(user.getUsername(),MD5Util.MD5EncodeUtf8(passwordnew));
        if(responseCount > 0){
            return ServerResponse.createBySuccessMessage("密码更改成功");
        }
        return  ServerResponse.createByErrorMessage("密码更新失败");
    }

    public ServerResponse<MmallUser> updateInfomation(MmallUser user) {
        int responseCount = mmallUserMapper.updateInfomation(user);
        if(responseCount > 0 ){
            return ServerResponse.createBySuccess(user);
        }else{
            return ServerResponse.createByErrorMessage("更新失败");
        }
    }

    public ServerResponse<MmallUser> getUserInformation(int id) {
        MmallUser user = mmallUserMapper.getUserInformation(id);
        if(user == null){
            return ServerResponse.createByErrorMessage("查找用户信息失败");
        }
        return  ServerResponse.createBySuccess(user);
    }


}
